package com.zhihuichongcheng.application.ui.cricle.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.LinearLayout;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.smartlib.cmnObject.util.DeviceUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseFragment;
import com.zhihuichongcheng.application.bean.cricle.HealthBean;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.ui.cricle.adapter.CricleHealthyAdapter;
import com.zhihuichongcheng.application.util.RecycleViewDivider;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 3water on 2016/10/28.
 */

public class CircleHealthyFragment extends BaseFragment {
    public static final String ACTION_UPDATE_HEALTHY_LIST = "action.update.healthy.list";
    private XRecyclerView mRcvHealthy;
    private List<HealthBean> mListData = new ArrayList<>();
    private CricleHealthyAdapter mAdapter = null;
    private String type;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private int mPageSize = 10;
    private int mPage = 1;
    private LinearLayout mLlNoData;

    //广播
    private MyBroadcastReceiver mReciver = new MyBroadcastReceiver();


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();

        registerReciver();

        if (bundle != null && bundle.containsKey("type")) {
            type = bundle.getString("type");
        }
    }

    private void registerReciver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_UPDATE_HEALTHY_LIST);
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(mReciver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegisterReciver();
    }

    private void unRegisterReciver() {
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mReciver);
    }

    @Override
    protected void init() {
        super.init();
        initView();
        initData();
    }

    private void initView() {
        mLlNoData = (LinearLayout) mView.findViewById(R.id.ll_nodata);
        mRcvHealthy = (XRecyclerView) mView.findViewById(R.id.rcv_healthy);
        mAdapter = new CricleHealthyAdapter(mContext);
        mAdapter.setUserId(mUser.getUserId());
        mRcvHealthy.setLayoutManager(new LinearLayoutManager(mContext));
        mRcvHealthy.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.VERTICAL, 10, getResources().getColor(R.color.white)));
        mRcvHealthy.setAdapter(mAdapter);
        mRcvHealthy.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mPage = 1;
                loadData(mPage);
            }

            @Override
            public void onLoadMore() {
                mPage++;
                loadData(mPage);
            }
        });
    }

    private void initData() {
        loadData(mPage);
        mAdapter.setData(mListData);
        mAdapter.notifyDataSetChanged();
    }

    /***
     * 加载每页的数据
     */
    private void loadData(final int page) {
        HashMap<String, String> param = new HashMap<>();
        param.put("token", mUser.getToken());
        param.put("jinbaoHomeCategoryId", type);
        param.put("pageRows", "" + mPageSize);
        param.put("curPage", "" + page);
        manager.post(NetworkAPI.CricleList, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                List<HealthBean> list = GsonUtil.paraeFromStringToList(value, HealthBean.class);
                if (page == 1) {
                    mAdapter.clear();
                    if (list.size() == 0) {
                        mLlNoData.setVisibility(View.VISIBLE);
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mLlNoData.getLayoutParams();
                        params.setMargins(0, (DeviceUtil.getHeight(mContext) - DeviceUtil.dip2px(mContext, 50)) / 10 * 4 - DeviceUtil.dip2px(mContext, 75), 0, 0);
                        mLlNoData.setLayoutParams(params);
                        mRcvHealthy.setVisibility(View.GONE);
                    } else {
                        mLlNoData.setVisibility(View.GONE);
                        mRcvHealthy.setVisibility(View.VISIBLE);
                    }
                }
                mAdapter.setData(list);
                mAdapter.notifyDataSetChanged();
                mRcvHealthy.loadMoreComplete();
                mRcvHealthy.refreshComplete();
                if (list.size() < mPageSize) {
                    mRcvHealthy.setNoMore(true);
                }

            }

            @Override
            public void onFailure(String value) {
                if (page == 1) {
                    mLlNoData.setVisibility(View.VISIBLE);
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mLlNoData.getLayoutParams();
                    params.setMargins(0, (DeviceUtil.getHeight(mContext) - DeviceUtil.dip2px(mContext, 50)) / 10 * 4 - DeviceUtil.dip2px(mContext, 75), 0, 0);
                    mLlNoData.setLayoutParams(params);
                    mRcvHealthy.setVisibility(View.GONE);
                }
            }
        }, param);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_cricle_healthy;
    }

    public void reflush() {
        mPage = 1;
        loadData(mPage);

    }

    public class MyBroadcastReceiver extends BroadcastReceiver {
        private static final String TAG = "MyBroadcastReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuilder sb = new StringBuilder();
            if (null != intent && null != intent.getAction()) {
                String action = intent.getAction();
                if (ACTION_UPDATE_HEALTHY_LIST.equals(action)) {
                    mPage = 1;
                    loadData(mPage);
                }
            }
        }
    }

}
